package com.cloud.lan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.BaseReq;
import com.cloud.lan.api.dto.req.DelReq;
import com.cloud.lan.api.dto.req.ImportEvaluateReq;
import com.cloud.lan.api.dto.req.LanGoodsEvaluateReq;
import com.cloud.lan.dao.LanGoodsEvaluateMapper;
import com.cloud.lan.dao.LanGoodsMapper;
import com.cloud.lan.dao.LanUserMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.enums.LanError;
import com.cloud.lan.entity.model.dataobject.LanGoodsDO;
import com.cloud.lan.entity.model.dataobject.LanGoodsEvaluateDO;
import com.cloud.lan.entity.model.dataobject.LanUserDO;
import com.cloud.lan.entity.utils.VocUtil;
import com.cloud.lan.service.ILanGoodsEvaluateService;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;

import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ONE;
import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ZERO;

/**
 * <p>
 * 商品评价信息表 服务实现类
 * </p>
 *
 * @author xyqierkang@163.com
 * @since 2022-05-21
 */
@Slf4j
@Service
public class LanGoodsEvaluateServiceImpl extends ServiceImpl<LanGoodsEvaluateMapper, LanGoodsEvaluateDO> implements ILanGoodsEvaluateService {

    @Resource
    LanGoodsEvaluateMapper lanGoodsEvaluateMapper;
    @Resource
    LanUserMapper lanUserMapper;
    @Resource
    LanGoodsMapper lanGoodsMapper;

    @Override
    public BaseResponse manageList(LanGoodsEvaluateReq req) {
        log.info("#查询 商品评价 列表 {}", req);
        LambdaQueryWrapper<LanGoodsEvaluateDO> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(LanGoodsEvaluateDO::getCreateTime);
        Page<LanGoodsEvaluateDO> page = new Page<>(req.getPageIndex(), req.getPageSize());
        if (req.getGoodsId() != null) {
            qw.eq(LanGoodsEvaluateDO::getGoodsId, req.getGoodsId());
        }
        if (StrUtil.isNotEmpty(req.getUserPhone())) {
            LanUserDO lanUserDO = lanUserMapper.getUserPhone(req.getUserPhone());
            qw.eq(LanGoodsEvaluateDO::getUserId, lanUserDO.getUserId());
        }
        IPage<LanGoodsEvaluateDO> pageList = lanGoodsEvaluateMapper.selectPage(page, qw);
        pageList.getRecords().forEach(p -> {
            LanGoodsDO lanGoodsDO = lanGoodsMapper.selectById(p.getGoodsId());
            LanUserDO lanUserDO = lanUserMapper.getUserId(p.getUserId());
            p.setGoodsName(lanGoodsDO.getName());
            p.setWxName(lanUserDO.getWxName());
            p.setWxHead(lanUserDO.getWxHead());
            p.setUserPhone(lanUserDO.getUserPhone());
        });
        return BaseResponse.success(pageList);
    }

    @Override
    public BaseResponse add(LanGoodsEvaluateReq req) {
        log.info("#新增 商品评价 {}", req);
        VocUtil.checkNullAttribute(new String[]{String.valueOf(req.getGoodsId()),
                        String.valueOf(req.getUserId()), req.getTitle(), req.getContent()},
                new String[]{"goodsId", "userId", "title", "content"}, LanError.ILLEGAL_PARAMS.getCode());
        LanGoodsEvaluateDO lanGoodsEvaluateDO = new LanGoodsEvaluateDO();
        BeanUtil.copyProperties(req, lanGoodsEvaluateDO);
        lanGoodsEvaluateMapper.insert(lanGoodsEvaluateDO);
        return BaseResponse.success();
    }

    @Override
    public BaseResponse update(LanGoodsEvaluateReq req) {
        log.info("#更新 商品评价 {}", req);
        VocUtil.checkNullAttribute(new String[]{String.valueOf(req.getId()), String.valueOf(req.getGoodsId()),
                        String.valueOf(req.getUserId()), req.getTitle(), req.getContent()},
                new String[]{"id", "goodsId", "userId", "title", "content"}, LanError.ILLEGAL_PARAMS.getCode());
        LanGoodsEvaluateDO lanGoodsEvaluateDO = lanGoodsEvaluateMapper.selectById(req.getId());
        BeanUtil.copyProperties(req, lanGoodsEvaluateDO);
        lanGoodsEvaluateMapper.updateById(lanGoodsEvaluateDO);
        return BaseResponse.success();
    }

    @Override
    public BaseResponse delete(DelReq req) {
        log.info("#删除 商品评价 {}", req);
        VocUtil.checkNullAttribute(new String[]{String.valueOf(req.getId())}, new String[]{"id"}, LanError.ILLEGAL_PARAMS.getCode());
        LambdaUpdateWrapper<LanGoodsEvaluateDO> luw = new LambdaUpdateWrapper<>();
        luw.set(LanGoodsEvaluateDO::getIsDeleted, ONE.getKey()).eq(LanGoodsEvaluateDO::getId, req.getId());
        lanGoodsEvaluateMapper.update(new LanGoodsEvaluateDO(), luw);
        return BaseResponse.success();
    }

    @Override
    public BaseResponse importEvaluate(@RequestHeader(BaseReq.ut) String token, @RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (!fileType.endsWith(".xls") && !fileType.endsWith(".xlsx")) {
            return BaseResponse.error(LanError.LAN_010010.getCode(), LanError.LAN_010010.getMsg());
        }
        List<Long> usList = new ArrayList<>();
        List<Long> goodsList = new ArrayList<>();
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), ZERO.getKey());
            List<ImportEvaluateReq> importEvaluateReqs = reader.readAll(ImportEvaluateReq.class);
            importEvaluateReqs.forEach(im -> {
                LanUserDO lanUserDO = lanUserMapper.getUserId(im.get用户ID());
                LanGoodsDO lanGoodsDO = lanGoodsMapper.selectById(im.get产品ID());
                if (ObjectUtil.isNotNull(lanUserDO) && ObjectUtil.isNotNull(lanGoodsDO)) {
                    log.error("{}", LanError.LAN_010011.getMsg());
                    usList.add(im.get用户ID());
                    goodsList.add(im.get产品ID());
                    LanGoodsEvaluateDO lanGoodsEvaluateDO = new LanGoodsEvaluateDO();
                    lanGoodsEvaluateDO.setUserId(im.get用户ID());
                    lanGoodsEvaluateDO.setGoodsId(im.get产品ID());
                    lanGoodsEvaluateDO.setTitle(im.get评价标题());
                    lanGoodsEvaluateDO.setContent(im.get用户评价());
                    Date nowD = new Date();
                    LambdaQueryWrapper<LanGoodsEvaluateDO> qw = new LambdaQueryWrapper<>();
                    qw.eq(LanGoodsEvaluateDO::getUserId, lanGoodsEvaluateDO.getUserId());
                    qw.eq(LanGoodsEvaluateDO::getGoodsId, lanGoodsEvaluateDO.getGoodsId());
                    qw.eq(LanGoodsEvaluateDO::getTitle, lanGoodsEvaluateDO.getTitle());
                    qw.eq(LanGoodsEvaluateDO::getContent, lanGoodsEvaluateDO.getContent());
                    LanGoodsEvaluateDO exitDO = lanGoodsEvaluateMapper.selectOne(qw);
                    if (Objects.isNull(exitDO)) {
                        lanGoodsEvaluateDO.setCreateTime(nowD);
                        lanGoodsEvaluateDO.setUpdateTime(nowD);
                        lanGoodsEvaluateMapper.insert(lanGoodsEvaluateDO);
                    }
                }
            });
        } catch (Exception e) {
            log.error("#异步线程 上传xls 失败 ", e);
            return BaseResponse.error(LanError.LAN_010010.getCode(), "导入失败");
        }
        return BaseResponse.success(StrUtil.format("已导入完成,其中usList：{}，goodsList：{}", JSONUtil.toJsonStr(usList), JSONUtil.toJsonStr(goodsList)));
    }

    @Override
    public BaseResponse<Object> topping(LanGoodsEvaluateReq req) {
        VocUtil.checkNullAttribute(new String[]{String.valueOf(req.getId())}, new String[]{"id"}, LanError.ILLEGAL_PARAMS.getCode());
        LanGoodsEvaluateDO lanGoodsEvaluateDO = lanGoodsEvaluateMapper.selectById(req.getId());
        if (ObjectUtil.isNotEmpty(req.getPinStatus()) && req.getPinStatus().equals(ONE.getKey())) {
            lanGoodsEvaluateDO.setSort(50);
        } else {
            lanGoodsEvaluateDO.setSort(lanGoodsEvaluateDO.getSort() > 9999 ? lanGoodsEvaluateDO.getSort() + 1 : 10000);
        }
        lanGoodsEvaluateMapper.updateById(lanGoodsEvaluateDO);
        return BaseResponse.success();
    }
}
